package cn.gov.pbc.tims.service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import com.sun.mail.pop3.POP3Folder;

import cn.gov.pbc.tims.entity.Fileup;
import cn.gov.pbc.tims.entity.Mail;
import cn.gov.pbc.tims.entity.User;
import cn.gov.pbc.tims.serviceInt.IMailService;
import cn.gov.pbc.tims.util.FileOperateUtil;
import cn.gov.pbc.tims.util.PageData;
@Service("pop3MailService")
public class Pop3MailService implements IMailService {

	@Override
	public POP3Folder getFolder(String userName,String password) throws MessagingException {
		ResourceBundle resource=ResourceBundle.getBundle("mailconfig");
        Properties prop = System.getProperties();  
        //String user = "kej.ta@sd.pbc.gov";// 邮箱的用户名      
        //String password = "sdtan0538"; // 邮箱的密码      
        //String beginDate=resource.getString("beginDate"); 
        //prop.put("mail.store.protocol", "imap"); 
        prop.put("mail.store.protocol", "pop3");
        //prop.put("mail.imap.host", "ywmail.pbc.gov"); 
       // prop.put("mail.imap.host", resource.getString("mail.imap.host"));
        prop.put("mail.pop3.host", resource.getString("mail.pop3.host"));
        Session session = Session.getInstance(prop);      
        Store  store =  session.getStore("pop3"); // 使用pop3会话机制，连接服务器      
        store.connect(userName, password); 
		POP3Folder folder = (POP3Folder)store.getFolder("INBOX");
		folder.open(Folder.READ_ONLY);
		return folder;
	}

	@Override
	public PageData getMail(Folder folder,Integer page, Integer rows,HttpServletRequest request) throws Exception {
		POP3Folder pop3Folder=(POP3Folder)folder;
		int total = 0;      
		Integer startRow=(page-1)*rows;
		Message[] messages=folder.getMessages();
		for(int i=0;i<messages.length-1;i++)
			for(int j=0;j<messages.length-1-i;j++)
			{
				if(null!=messages[j].getSentDate()&&null!=messages[j+1].getSentDate())
				if(messages[j].getSentDate().compareTo(messages[j+1].getSentDate())<0)
				{	
					Message temp = messages[j+1];        // 元素交换
					messages[j+1] = messages[j];
					messages[j] = temp;
					}
			}
		total=messages.length;
		System.out.println(Calendar.getInstance().getTime().getSeconds());
		
	/*	if(total>=startRow+rows)
			 messages = folder.getMessages(startRow, startRow+rows-1);
		else
			  messages = folder.getMessages(startRow, total);*/
		//System.out.println("邮件数量:　" + total);
		 
		int nub=0;
		if(total>=startRow+rows)
	    	nub=rows;
		else
			nub=total-startRow;
		Mail re = null;
		List results=new ArrayList<Mail>();

		for (int i = startRow; i < startRow+nub; i++) {
			MimeMessage message=(MimeMessage) messages[i];
			re = new Mail(message,((POP3Folder)folder).getUID(message));
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			//if(sdf.parse(beginDate).before(sdf.parse(re.getSentDate())))
			results.add(re);
		}
		PageData grid_data=new PageData();
		grid_data.setValue(total, results);
		folder.close();
        folder.getStore().close();
		System.out.println(Calendar.getInstance().getTime().getSeconds());
     return grid_data;
	}
	@Override
	public MimeMessage getMessageByUid(Folder folder,String uid) throws MessagingException
	{
		MimeMessage message1=null;
		Message [] messages= folder.getMessages();
		for (int i=0;i<messages.length;i++)
		{
		    MimeMessage message=(MimeMessage)messages[i];
		    if(((POP3Folder)folder).getUID((MimeMessage) message).equals(uid))
			{
				message1=message;
				break;
			} 
		}
		return message1;
	}
	
	@Override
	public void getAttachment(Folder folder,String uid,String fileName,HttpServletRequest request, HttpServletResponse response) throws IOException, Exception {
		MimeMessage message1=getMessageByUid((POP3Folder)folder,uid);
		Mail mail=new Mail(message1);
		InputStream iss=mail.getAttachment(fileName,message1);
	    String contentType = "application/force-download";  
	    long fileLength = iss.available();  
	    System.out.println("fileLength is"+fileLength);
	    FileOperateUtil.download(request, response, contentType,fileName,iss); 
	    folder.close();
		folder.getStore().close(); 
	}
	public InputStream getAttachmentInputStream(Folder folder,String uid,String fileName,HttpServletRequest request, HttpServletResponse response) throws IOException, Exception {
		MimeMessage message1=getMessageByUid((POP3Folder)folder,uid);
		Mail mail=new Mail(message1);
		InputStream iss=mail.getAttachment(fileName,message1);
	    folder.close();
		folder.getStore().close(); 
		return iss;
	}
	@Override
	public String getDocContent(Folder folder,String uid,String fileName,HttpServletRequest request, HttpServletResponse response) throws Exception {
		String content="";
		MimeMessage message1=getMessageByUid((POP3Folder)folder,uid);
		Mail mail=new Mail(message1);
			InputStream iss=mail.getAttachment(fileName,message1);
			System.out.println(iss.available());
			
			if(fileName.endsWith(".doc")||fileName.endsWith(".docx"))
			{
				content=FileOperateUtil.readWord(iss, ".doc");
			}
			else if(fileName.endsWith(".docx"))
			{
				content=FileOperateUtil.readWord(iss, ".docx") ;
			}
			else if(fileName.endsWith(".wps"))
			{
				content=FileOperateUtil.readWord(iss, ".doc");
			}
			else if(fileName.endsWith(".pdf"))
			 {
				content=FileOperateUtil.readPdf(iss);
			  }
			else
			 {
				content=FileOperateUtil.readTxt(iss);
			  }
			
			folder.close();
			folder.getStore().close();
			return content;
	}
	  
}
